const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const notificationService = require('./notification.service');

/**
 * 销毁指定日期之前的所有考试数据
 * @param {string} beforeDate - 销毁该日期之前的所有考试数据
 * @returns {Promise<object>} - 操作结果
 */
async function destroyOldExaminations(beforeDate) {
  try {
    console.log(`开始销毁 ${beforeDate} 之前的所有考试数据...`);
    
    // 查询需要销毁的考试
    const examinations = await prisma.examination.findMany({
      where: {
        end_time: {
          lt: new Date(beforeDate)
        }
      },
      select: {
        id: true,
        name: true,
        user_id: true
      }
    });

  
    
    if (examinations.length === 0) {
      console.log('没有需要销毁的考试数据');
      return { 
        success: true, 
        message: '没有找到需要销毁的考试数据', 
        data: { count: 0 } 
      };
    }
    
    console.log(`找到 ${examinations.length} 个需要销毁的考试`);
    
    // 记录每个考试的销毁结果
    const destroyResults = [];
    let totalDeletedPapers = 0;
    
    // 依次销毁每个考试的数据
    for (const examination of examinations) {
      const result = await destroyExaminationPapers(examination.id);
      destroyResults.push({
        examinationId: examination.id,
        examinationName: examination.name,
        success: result.success,
        deletedPapers: result.data?.count || 0
      });
      
      if (result.success) {
        totalDeletedPapers += result.data?.count || 0;
      }
    }
    
    return {
      success: true,
      message: `成功销毁 ${examinations.length} 个考试的数据`,
      data: {
        count: examinations.length,
        totalDeletedPapers,
        details: destroyResults
      }
    };
  } catch (error) {
    console.error('销毁旧考试数据时发生错误:', error);
    return {
      success: false,
      message: '销毁旧考试数据失败',
      error: error.message,
      code: 500
    };
  }
}

/**
 * 销毁指定考试的所有试卷数据
 * @param {number} examinationId - 考试ID
 * @returns {Promise<object>} - 操作结果
 */
async function destroyExaminationPapers(examinationId) {
  try {
    // 查询考试是否存在
    const examination = await prisma.examination.findUnique({
      where: { id: Number(examinationId) }
    });
    
    if (!examination) {
      return { success: false, message: '考试不存在', code: 404 };
    }
    
    // 开始数据库事务，确保所有数据操作都成功或者都失败
    return await prisma.$transaction(async (tx) => {
      // 1. 获取该考试的所有学生试卷
      const studentPapers = await tx.student_paper.findMany({
        where: { examination_id: Number(examinationId) },
        select: { id: true }
      });
      
      const studentPaperIds = studentPapers.map(paper => paper.id);
      
      if (studentPaperIds.length === 0) {
        return { success: true, message: '该考试没有试卷数据', data: { count: 0 } };
      }
      
      // 2. 删除所有相关的复审结果记录
      const recheckRequests = await tx.recheck_request.findMany({
        where: { student_paper_id: { in: studentPaperIds } },
        select: { id: true }
      });
      
      const recheckRequestIds = recheckRequests.map(req => req.id);
      
      if (recheckRequestIds.length > 0) {
        // 删除复审结果
        await tx.recheck_result.deleteMany({
          where: { recheck_request_id: { in: recheckRequestIds } }
        });
        
        // 获取所有复审任务
        const rechecks = await tx.recheck.findMany({
          where: { recheck_request_id: { in: recheckRequestIds } },
          select: { id: true }
        });
        
        const recheckIds = rechecks.map(recheck => recheck.id);
        
        if (recheckIds.length > 0) {
          // 删除复审详情
          await tx.recheck_detail.deleteMany({
            where: { recheck_id: { in: recheckIds } }
          });
          
          // 删除复审任务
          await tx.recheck.deleteMany({
            where: { id: { in: recheckIds } }
          });
        }
        
        // 删除查卷申请
        await tx.recheck_request.deleteMany({
          where: { id: { in: recheckRequestIds } }
        });
      }
      
      // 3. 获取并删除批阅任务相关数据
      const reviewAssignments = await tx.review_assignment.findMany({
        where: { examination_id: Number(examinationId) },
        select: { id: true }
      });
      
      const reviewAssignmentIds = reviewAssignments.map(assignment => assignment.id);
      
      if (reviewAssignmentIds.length > 0) {
        // 删除批阅任务详情
        await tx.review_assignment_detail.deleteMany({
          where: { review_assignment_id: { in: reviewAssignmentIds } }
        });
        
        // 删除提醒日志
        await tx.reminder_log.deleteMany({
          where: { review_assignment_id: { in: reviewAssignmentIds } }
        });
        
        // 删除批阅任务
        await tx.review_assignment.deleteMany({
          where: { id: { in: reviewAssignmentIds } }
        });
      }
      
      // 4. 删除试卷详情
      await tx.paper_detail.deleteMany({
        where: { student_paper_id: { in: studentPaperIds } }
      });
      
      // 5. 删除学生试卷
      const deletedPapers = await tx.student_paper.deleteMany({
        where: { id: { in: studentPaperIds } }
      });
      
      // 6. 创建系统通知记录
      // await tx.system_notification.create({
      //   data: {
      //     recipient_id: examination.user_id,
      //     notification_type_id: 1, // 假设1为系统通知类型
      //     content: `考试"${examination.name}"的所有试卷数据已被系统自动销毁`,
      //     is_read: 0,
      //     create_time: new Date()
      //   }
      // });
      
      return {
        success: true,
        message: '试卷数据销毁成功',
        data: {
          count: deletedPapers.count,
          examinationName: examination.name
        }
      };
    });
  } catch (error) {
    console.error('销毁试卷数据时发生错误:', error);
    return {
      success: false,
      message: '销毁试卷数据失败',
      error: error.message,
      code: 500
    };
  }
}

module.exports = {
  destroyOldExaminations,
  destroyExaminationPapers
};